"""工具模块"""
from flask import current_app
import jwt
import datetime
from flask_restful import fields


# 生成jwt 信息
def jwt_encode(user):
    datetime_int = datetime.datetime.utcnow() + datetime.timedelta(seconds=7*60*60*24)
    # print(datetime_int)
    option = {
        'exp': datetime_int,
        'user': user
    }
    encoded = jwt.encode(option, current_app.config['SECRET_KEY'], algorithm='HS256').decode('utf-8')
    return encoded


# 解析jwt 信息
def jwt_decode(token):
    try:
        decoded = jwt.decode(token, current_app.config['SECRET_KEY'], algorithms=['HS256'])
    except jwt.ExpiredSignatureError as e:
        raise e
    return decoded


# 日期格式化
def fmt_date(time, time_format):
    if not time_format:
        time_format = '%Y-%m-%d %H:%M:%S'
    return time.strftime(time_format)


# 生成订单号
def generate_order_no(user_id):
    time = fmt_date(datetime.datetime.utcnow(), '%Y%m%d%H%M%S')
    return time + str(user_id)


class SimpleDateField(fields.Raw):

    def format(self, dt):
        return datetime.datetime.strftime(dt, '%Y-%m-%d %H:%M:%S')
